package org.atovio.structure.application;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Winter Yuan
 * @version 1.0
 * @organization AtoVio
 */
public class Operators implements Comparator<String> {

    /*
    运算符优先级映射
     */
    public static final Map<String, Integer> OPRATOR_MAP = new HashMap<>();

    public Operators() {
        // 运算符集合。
        String[] operator = {"*", "/", "%", "+", "-", "&", "^", "|"};
        // operator中相同下标运算符的优先级，值小的优先级高。
        int[] priority = {3, 3, 3, 4, 4, 8, 9, 10};
        for (int i = 0; i < operator.length; i++) {
            OPRATOR_MAP.put(operator[i], priority[i]);
        }
    }

    /**
     * 比较两个运算符的优先级大小
     *
     * @param oper1 运算符1
     * @param oper2 运算符2
     * @return -1表示运算符1优先级高，0表示二者相等，1表示运算符2优先级高。
     */
    @Override
    public int compare(String oper1, String oper2) {
        return OPRATOR_MAP.get(oper1) - OPRATOR_MAP.get(oper2);
    }

    public int operate(int x, int y, String oper) {
        int value = 0;
        switch (oper) {
            case "+" -> value = x + y;
            case "-" -> value = x - y;
            case "*" -> value = x * y;
            case "/" -> value = x / y;
            case "%" -> value = x % y;
            case "&" -> value = x & y;
            case "^" -> value = x ^ y;
            case "|" -> value = x | y;
        }
        return value;
    }
}
